﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using QunProject.Common;
using EnumHelpaer = QunProject.Model.EnumHelper;
using System.IO;

namespace QunProject.Manage.Controllers
{
    public class BaseController : Controller
    {
        /// <summary>
        /// 换成实例
        /// </summary>
        public Cache.ICache Cache = QunProject.Cache.ExampleCache.GetExampleCache();
        /// <summary>
        /// EF操作实例
        /// </summary>
        public Model.QunProjectEntities EF = new Model.QunProjectEntities();
        /// <summary>
        /// 返回数据对象
        /// </summary>
        public Common.Result Result = new Common.Result();
        /// <summary>
        /// 短信操作对象
        /// </summary>
        public Common.SmsHelper Sms = new Common.SmsHelper();
        /// <summary>
        /// 文件服务地址
        /// </summary>
        public string FileApiUrl = System.Configuration.ConfigurationManager.AppSettings["FileApiUrl"].ToString();
        /// <summary>
        /// 站点域名
        /// </summary>
        public string DomainUrl = System.Configuration.ConfigurationManager.AppSettings["DomainUrl"].ToString();
        /// <summary>
        /// 默认密码
        /// </summary>
        public string UserDefaultPassword = System.Configuration.ConfigurationManager.AppSettings["UserDefaultPassword"].ToString();
        /// <summary>
        /// 登录用户
        /// </summary>
        public Model.sys_user LoginUser
        {
            //get
            //{
            //    Model.sys_user _user = null;
            //    if (Cache.Get("system_user") != null)
            //    {
            //        _user = (Model.sys_user)Cache.Get("system_user");
            //    }
            //    return _user;
            //}
            //set
            //{
            //    Cache.Set("system_user", value);
            //}
            get
            {
                Model.sys_user _user = null;
                if (Session["system_user"] != null)
                {
                    _user = (Model.sys_user)Session["system_user"];
                }
                return _user;
            }
            set
            {
                Session["system_user"] = value;
            }
        }
        /// <summary>
        /// 知识分类
        /// </summary>
        public List<Model.classify> Classify
        {
            get
            {
                List<Model.classify> _list = null;
                if (Cache.Get("classify_cache") != null)
                {
                    _list = (List<Model.classify>)Cache.Get("classify_cache");
                }
                return _list;
            }
            set
            {
                Cache.Set("classify_cache", value);
            }
        }
        /// <summary>
        /// 登录验证码
        /// </summary>
        public string LoginCode
        {
            get
            {
                string _code = string.Empty;
                if (Cache.Get("login_code") != null)
                {
                    _code = (string)Cache.Get("login_code");
                }
                return _code;
            }
            set
            {
                Cache.Set("login_code", value, 2);
            }
        }
        /// <summary>
        /// 排除验证的URL
        /// </summary>
        public string[] ExcludeUrl = new string[] {
            "",
            "/login",
            "/login/index",
            "/login/ajaxlogincode",
            "/login/ajaxloginsubmit"
        };

        /// <summary>
        /// 进入方法时
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewBag.DomainTitle = "CoderTalking";
            string action = filterContext.HttpContext.Request.Url.AbsolutePath.ToLower();
            if (!ExcludeUrl.Contains(action))
            {
                if (LoginUser == null)
                {
                    if (Request.IsAjaxRequest())
                    {
                        Response.Clear();
                        Response.Write(Result.OutTime().ToJson());
                        Response.End();
                    }
                    else
                    {
                        Response.Clear();
                        Response.Write("<script>window.parent.parent.location = '/login/index';</script>");
                        Response.End();
                    }
                }
                else
                {
                    ViewBag.LoginUser = LoginUser;
                    ViewBag.UserDefaultPassword = UserDefaultPassword;

                    #region 知识分类

                    var cacheClassify = Classify;
                    if (cacheClassify != null)
                    {
                        ViewBag.Classify = cacheClassify;
                    }
                    else
                    {
                        Classify = EF.classify.Where(x => true).ToList();
                        ViewBag.Classify = Classify;
                    }

                    #endregion

                    #region 文件地址

                    var cacheFileApiUrl = Cache.Get("file_api_url");
                    if (cacheFileApiUrl != null)
                    {
                        ViewBag.FileApiUrl = cacheFileApiUrl.ToString();
                    }
                    else
                    {
                        Cache.Set("file_api_url", FileApiUrl);
                        ViewBag.FileApiUrl = FileApiUrl;
                    }

                    #endregion

                    #region 菜单

                    var cacheMenu = Cache.Get("system_menu");
                    if (cacheMenu != null)
                    {
                        ViewBag.MenuList = (List<Model.sys_menu>)cacheMenu;
                    }
                    else
                    {
                        var menuList = EF.sys_menu.Where(x => x.IsValid.Value).Select(x => x).ToList();//.AsNonUnicode();
                        Cache.Set("system_menu", menuList, 1440);
                        ViewBag.MenuList = menuList;
                    }

                    #endregion
                }
            }
        }

        /// <summary>
        /// 获取组合对象值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="methodName">方法名</param>
        /// <returns></returns>
        public System.Collections.Generic.Dictionary<string, string> WeaveParameters<T>(string methodName) where T : new()
        {
            Type type = typeof(T);
            List<string> paraNames = new List<string>();
            foreach (var method in type.GetMethods())
            {
                if (method.Name == methodName)
                {
                    foreach (var para in method.GetParameters())
                    {
                        paraNames.Add(para.Name);
                    }
                    break;
                }
            }
            System.Collections.Generic.Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>();
            foreach (var para in paraNames)
            {
                dic.Add(para, Request[para]);
            }
            return dic;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="type">上传图片方式</param>
        /// <param name="_base64">base64字符串</param>
        /// <returns></returns>
        public JsonResult Upload(int type = (int)FileHelper.FileTypes.不限制, string _base64 = "")
        {
            if (!_base64.IsNullOrWhiteSpace())
            {
                FileHelper.FileUpload file = new FileHelper.FileUpload(FileHelper.FileTypes.图片);
                string data = file.Base64(_base64);
                if (!data.IsNullOrWhiteSpace())
                    return Json(Result.Success(data));
                else
                    return Json(Result.Fail(file.ErrorMag));
            }
            else
            {
                if (Request.Files.Count > 0)
                {
                    FileHelper.FileUpload file = new FileHelper.FileUpload((FileHelper.FileTypes)Enum.Parse(typeof(FileHelper.FileTypes), type.ToString()));
                    string data = string.Empty;
                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        data += file.HttpPosted(Request.Files[i]) + ',';
                    }
                    data = data.TrimEnd(new[] { ',' });

                    if (!data.IsNullOrWhiteSpace())
                        return Json(Result.Success(data));
                    else
                        return Json(Result.Fail(file.ErrorMag));
                }
                else
                {
                    return Json(Result.Fail("文件数量为0"));
                }
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public JsonResult WangEditorUpload()
        {
            var files = Request.Files;
            if (files.Count <= 0)
                return Json("error|请选择上传的文件");


            List<string> imgList = new List<string>();

            //相对路径
            string relativePath = $"/Upload/WangEditor/{DateTime.Now.ToString("yyyy/MM/dd/")}";
            //绝对路径
            string absolutePath = Server.MapPath(relativePath);
            if (!Directory.Exists(absolutePath))
                Directory.CreateDirectory(absolutePath);

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFileBase file = files[i];
                //源文件名
                string sourceFileName = file.FileName;
                //文件后缀名
                string fileExtension = sourceFileName.Substring(sourceFileName.LastIndexOf('.'), sourceFileName.Length - sourceFileName.LastIndexOf('.'));
                //新文件名
                string currentFileName = Guid.NewGuid().ToString("N") + fileExtension;
                //文件保存路径
                string imagePath = absolutePath + currentFileName;
                //保存文件相对路径
                var path = relativePath + currentFileName;
                //保存文件
                file.SaveAs(imagePath);
                //获取图片url地址
                string imgUrl = DomainUrl + path;
                imgList.Add(imgUrl);
            }

            var data = new { errno = 0, data = imgList };
            return Json(data);
        }
    }
}